<?php

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    /**
    * Description of GoldParserService
    *
    * @author flexica team
    */
    class GoldParserService extends FServiceBase {


        public function getGoldRate($params) {
            //$this->getGlobalGoldPrice();
            $this->getExchange();
            //$this->sjcTTTuDo();

            echo 'finished';
            return $this->result;
        }
        /**
         * Get world gold price
         * @return FServiceModel
         * @throws CHttpException
         */
        public function getGlobalGoldPrice(){
            $link = 'http://www.kitco.com/';
            $html = Helper::curlRequest($link);
            //$html= fixCData($html);
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);
            $buy=$xpath->query('//table[@id="main_container"]/tr/td[1]/div[@class="item_container"][3]/div[@class="item_border"]/table/tr[1]/td[2]');
            $sell=$xpath->query('//table[@id="main_container"]/tr/td[1]/div[@class="item_container"][3]/div[@class="item_border"]/table/tr[1]/td[3]');
            if($buy->length>0){
                $buyValue=str_replace(' ','',str_replace('-','',$buy->item(0)->nodeValue));
                $buyValue=doubleval($buyValue);
                $buyValue=number_format($buyValue,2,'.',',');
            }
            else $buyValue= 'null';
            if($sell->length>0){
                $sellValue= str_replace(' ','',$sell->item(0)->nodeValue);
                $sellValue=doubleval($sellValue);
                $sellValue=number_format($sellValue,2,'.',',');
            }
            else $sellValue= 'null';

            $this->saveGoldPrice(array(
            'name'=>'Vàng TG(USD)',
            'buy'=>$buyValue,
            'sell'=>$sellValue,
            'pos'=>1
            ));
            return $this->result;
        }

        public function getExchange(){


            $link='http://www.samco.com.vn/rss.php?function=ti_gia_ngoai_te';
            //$link='http://sjc.com.vn/xml/tygiavang.xml';
            $html = Helper::curlRequest($link);
            //echo $html;die;
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);


            //Get official table
            $buy = $xpath->query('//table[2]/tr[6]/td[2]');
            $sell = $xpath->query('//table[2]/tr[6]/td[4]');

            if($buy->length>0){
                $buyValue=$buy->item(0)->nodeValue;
//                $buyValue=str_replace(' ','',str_replace(',','',$buy->item(0)->nodeValue));
//                $buyValue=doubleval($buyValue)/100;
//                $buyValue=number_format($buyValue,0,',','.');
            }
            else $buyValue= 'null';

            if($sell->length>0){
                $sellValue=$sell->item(0)->nodeValue;
//                $sellValue= str_replace(' ','',str_replace(',','',$sell->item(0)->nodeValue));
//                $sellValue=doubleval($sellValue)/100;
//                $sellValue=number_format($sellValue,0,',','.');
            }
            else $sellValue= 'null';

            $this->saveGoldPrice(array(
                'name'=>'USD (VCB)',
                'buy'=>$buyValue,
                'sell'=>$sellValue,
                'pos'=>3
            ));

            //Get official table
            $buy = $xpath->query('//table[2]/tr[3]/td[2]');
            $sell = $xpath->query('//table[2]/tr[3]/td[4]');

            if($buy->length>0){
                $buyValue=$buy->item(0)->nodeValue;
//                $buyValue=str_replace(' ','',str_replace(',','',$buy->item(0)->nodeValue));
//                $buyValue=doubleval($buyValue)/100;
//                $buyValue=number_format($buyValue,0,',','.');
            }
            else $buyValue= 'null';

            if($sell->length>0){
                $sellValue=$sell->item(0)->nodeValue;
//                $sellValue= str_replace(' ','',str_replace(',','',$sell->item(0)->nodeValue));
//                $sellValue=doubleval($sellValue)/100;
//                $sellValue=number_format($sellValue,0,',','.');
            }
            else $sellValue= 'null';

            $this->saveGoldPrice(array(
                'name'=>'EUR (VCB)',
                'buy'=>$buyValue,
                'sell'=>$sellValue,
                'pos'=>4
            ));
            return $this->result;
        }

        /**
         * Get gold price from ACB .
         * @return FServiceModel
         * @throws CHttpException
         */
        public function sjcAcb(){
            $link='http://www.acb.com.vn/tygia/';
            $html = Helper::curlRequest($link);
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);
            //Get official table
            $buy = $xpath->query('//html/body/table/tr[4]/td[2]/table/tr[3]/td[2]');
            $sell = $xpath->query('//html/body/table/tr[4]/td[2]/table/tr[3]/td[4]');

            if($buy->length>0){
                $buyValue=str_replace(' ','',str_replace(',','',$buy->item(0)->nodeValue));
                $buyValue=doubleval($buyValue)/100;
                $buyValue=number_format($buyValue,0,',','.');
            }
            else $buyValue= 'null';

            if($sell->length>0){
                $sellValue= str_replace(' ','',str_replace(',','',$sell->item(0)->nodeValue));
                $sellValue=doubleval($sellValue)/100;
                $sellValue=number_format($sellValue,0,',','.');
            }
            else $sellValue= 'null';

            $this->saveGoldPrice(array(
            'name'=>'SJC ACB',
            'buy'=>$buyValue,
            'sell'=>$sellValue,
            'pos'=>5
            ));
            return $this->result;

        }
        /**
         * Get SJC Sacombank gold price
         * @return FServiceModel
         * @throws CHttpException
         */
        public function sjcSacombank(){
            $link='http://www.sacombank.com.vn/Pages/default.aspx';
            $html = Helper::curlRequest($link);
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);

            //Get official table
            $buy = $xpath->query('//div[@id="country2"]/table/tr[2]/td[2]');
            $sell = $xpath->query('//div[@id="country2"]/table/tr[2]/td[3]');

            if($buy->length>0){
                $buyValue=str_replace(' ','',str_replace(',','',$buy->item(0)->nodeValue));
                $buyValue=doubleval($buyValue)/100;
                $buyValue=number_format($buyValue,0,',','.');
            }
            else $buyValue= 'null';

            if($sell->length>0){
                $sellValue= str_replace(' ','',str_replace(',','',$sell->item(0)->nodeValue));
                $sellValue=doubleval($sellValue)/100;
                $sellValue=number_format($sellValue,0,',','.');
            }
            else $sellValue= 'null';

            $this->saveGoldPrice(array(
            'name'=>'SJC SACOMBANK',
            'buy'=>$buyValue,
            'sell'=>$sellValue,
            'pos'=>6
            ));
            return $this->result;

        }

        /**
         * Get SJC Eximbank
         * @return FServiceModel
         * @throws CHttpException
         */
        public function sjcEximbank(){
            $link='http://www.eximbank.com.vn/WebsiteExrate2011/ExchangeRate_vn_2011.aspx';
            $html = Helper::curlRequest($link);
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);

            //Get official table
            $buy = $xpath->query('//span[@id="GoldRateRepeater_ctl01_lblCSHBUYRT"]');
            $sell = $xpath->query('//span[@id="GoldRateRepeater_ctl01_lblCSHSELLRT"]');

            if($buy->length>0){
                $buyValue=str_replace(' ','',str_replace(',','',$buy->item(0)->nodeValue));
                $buyValue=doubleval($buyValue)/100;
                $buyValue=number_format($buyValue,0,',','.');
            }
            else $buyValue= 'null';

            if($sell->length>0){
                $sellValue= str_replace(' ','',str_replace(',','',$sell->item(0)->nodeValue));
                $sellValue=doubleval($sellValue)/100;
                $sellValue=number_format($sellValue,0,',','.');
            }
            else  $sellValue= 'null';

            $this->saveGoldPrice(array(
            'name'=>'SJC EXIMBANK',
            'buy'=>$buyValue,
            'sell'=>$sellValue,
            'pos'=>4
            ));
            return $this->result;
        }
        /**
         * Get price from Bao tin minh chau
         * @return FServiceModel
         * @throws CHttpException
         */
        public function sjcBtmc(){
            $link='btmc.vn';
            $html = Helper::curlRequest($link);
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);

            $buy = $xpath->query('//table[@id="dnn_ctr405_Market_GridView1"]/tr[4]/td[4]');
            $sell = $xpath->query('//table[@id="dnn_ctr405_Market_GridView1"]/tr[4]/td[5]');

            if($buy->length>0){
                $buyValue=str_replace(' ','',str_replace('.','',$buy->item(0)->nodeValue));
                $buyValue=doubleval($buyValue)/100;
                $buyValue=number_format($buyValue,0,',','.');
            }
            else $buyValue= 'null';

            if($sell->length>0){
                $sellValue= str_replace(' ','',str_replace('.','',$sell->item(0)->nodeValue));
                $sellValue=doubleval($sellValue)/100;
                $sellValue=number_format($sellValue,0,',','.');
            }
            else  $sellValue= 'null';

            $this->saveGoldPrice(array(
            'name'=>'SJC BTMC',
            'buy'=>$buyValue,
            'sell'=>$sellValue,
            'pos'=>7
            ));
            return $this->result;
        }
        /**
         * Get gold from Can tho
         * @return FServiceModel
         * @throws CHttpException
         */
        public function sjcCantho(){
            $link='http://sjccantho.vn/libs/giavang.php?where=cantho';
            $html = Helper::curlRequest($link);
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);

            //Get official table
            $buy = $xpath->query('//table[@id="oranges"]/tr[1]/td[2]');
            $sell = $xpath->query('//table[@id="oranges"]/tr[1]/td[3]');

            if($buy->length>0){
                $buyValue=str_replace(' ','',str_replace(',','.',$buy->item(0)->nodeValue));
            }
            else  $buyValue= 'null';

            if($sell->length>0){
                $sellValue= str_replace(' ','',str_replace(',','.',$sell->item(0)->nodeValue));
            }
            else  $sellValue= 'null';

            $this->saveGoldPrice(array(
            'name'=>'SJC Cần thơ',
            'buy'=>$buyValue,
            'sell'=>$sellValue,
            'pos'=>3
            ));
            return $this->result;
        }

        /**
         * Get free gold price
         * @return FServiceModel
         * @throws CHttpException
         */
        public function sjcTTTuDo(){
            $link='http://vip.giavang.net/data/PriceTableFP.asp';
            $html = Helper::curlRequest($link);
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);
            //Save sjc_market table
            $buy = $xpath->query('//div[@align="center"]/table/tr/td/table[2]/tbody/tr[4]/td[2]');
            $sell = $xpath->query('//div[@align="center"]/table/tr/td/table[2]/tbody/tr[4]/td[3]');

            if($buy->length>0){
                $buyValue=str_replace(' ','',str_replace(',','',$buy->item(0)->nodeValue));
                $buyValue=doubleval($buyValue)/1000;
                $buyValue=number_format($buyValue,0,',','.');
            }
            else $buyValue= 'null';

            if($sell->length>0){
                $sellValue= str_replace(' ','',str_replace(',','',$sell->item(0)->nodeValue));
                $sellValue=doubleval($sellValue)/1000;
                $sellValue=number_format($sellValue,0,',','.');
            }
            else  $sellValue= 'null';

            $this->saveGoldPrice(array(
            'name'=>'Vàng SJC',
            'buy'=>$buyValue,
            'sell'=>$sellValue,
            'pos'=>2
            ));
            return $this->result;
        }
        /**
         * SJC HCM
         * @return FServiceModel
         * @throws CHttpException
         */
        public function sjcHcm(){
            $link='http://sjc.com.vn/xml/tygiavang.xml';
            $html = Helper::curlRequest($link);
            $doc = Helper::createXMLDocFromHTML($html);
            if (!is_object($doc))
                throw new CHttpException(404, 'Error when creating XML DOC');
            $xpath = new DOMXPath($doc);
            $sjcPath=$xpath->query('//city[@name="Hồ Chí Minh"]/item[1]');
            if($sjcPath->length>0){
               $buy=$sjcPath->item(0)->getAttribute('buy');
               $sell=$sjcPath->item(0)->getAttribute('sell');
            }
            $this->saveGoldPrice(array(
            'name'=>'SJC HCM',
            'buy'=>$buy,
            'sell'=>$sell,
            'pos'=>2
            ));
            return $this->result;
        }
        
        public function getVietComBankExchange()
        {
            $url = 'http://www.vietcombank.com.vn/ExchangeRates/ExrateXML.aspx';
            $doc = new DOMDocument();
            $doc->load($url);
            $nodeExrates = $doc->getElementsByTagName('Exrate');
            $pos = 1;
            $current_date = date('Y-m-d');
            $res_str = 'Currency in : '.$current_date.'<br />';
            foreach($nodeExrates as $node)
            {
                $currency_code = trim($node->getAttribute('CurrencyCode'));
                if (in_array($currency_code,array('USD','EUR','AUD','MYR','KRW','SGD')))
                {
                    $model = GoldRate::model()->findByAttributes(array('code' =>$currency_code));
                    if(is_null($model))
                        $model=new GoldRate();
                    $model->code = $currency_code;
                    $model->name = trim($node->getAttribute('CurrencyName')); 
                    $model->buy = trim($node->getAttribute('Buy'));
                    if ($model->buy==0)
                        $model->buy = trim($node->getAttribute('Transfer'));
                    //$model->buy = floatval($model->buy);
                    $model->buy = number_format($model->buy,2);
                    $model->sell = number_format(trim($node->getAttribute('Sell')),2);
                    $model->date = $current_date;
                    $model->pos=$pos;
                    if ($model->save(false))
                    {
                        $pos++;
                        $res_str .= $model->code." ({$model->name}) ".' - Buy : '.$model->buy.' - Sell : '.$model->sell.' - position : '.$model->pos.'<br />';
                    }
                }
            }
            $this->result->processed('result_string',$res_str);
            return $this->result;
        }

        /**
         * Save to gold_rate table with all values as params values.
         * @param $params
         * @return mixed
         */
        private function saveGoldPrice($params){
            $date=date('Y-m-d');
            $name=$this->getParam($params,'name');
            $buy=$this->getParam($params,'buy');
            $sell=$this->getParam($params,'sell');
            $pos=$this->getParam($params,'pos');
            $model = GoldRate::model()->findByAttributes(array('name' =>$name));
            if(!$model)
                $model=new GoldRate();
            $model->name=$name;
            $model->buy=$buy;
            $model->sell=$sell;
            $model->date=$date;
            $model->pos=$pos;
            return $model->save(false);
        }

    }

?>
